package info.batcloud.fanli.core.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import info.batcloud.fanli.core.aliyun.OSSConfig;
import info.batcloud.fanli.core.constants.CacheNameConstants;
import info.batcloud.fanli.core.service.OssService;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

@Service
@CacheConfig(cacheNames = CacheNameConstants.OSS)
public class OssServiceImpl implements OssService {

    @Inject
    private OSSClient ossClient;

    @Inject
    private OSSConfig ossConfig;

    @Cacheable(key = "'OBJECT_META_' + #key")
    public String getObjectName(String key) {
        ObjectMetadata objectMeta = ossClient.getObjectMetadata(ossConfig.getBucket(), key);
        if(objectMeta.getUserMetadata().containsKey("filename")) {
            try {
                return URLDecoder.decode(objectMeta.getUserMetadata().get("filename"), "utf8");
            } catch (UnsupportedEncodingException e) {
                return null;
            }
        }
        return null;
    }
}
